<template>
    <div class="video">
        <!--audio src="down/mp3/Downs1530235581268.mp3" controls="controls">
        </audio-->
        <div  class="start_btn">
            <button>按住录音</button>
        </div>
        <div  class="play_btn">
            <button>点我播放</button>
        </div>
        <div  class="send_btn" >
            <button>点我保存</button>
        </div>
        <div  class="down_btn" >
            <button>下载</button>
        </div>
    </div>     
</template>

<script>
import wx from 'weixin-js-sdk'
import Api from '@/api/Api'
import {wapCookie} from '@/utils/Constant'
export default {
    name : 'Wechat',
    mounted () {
        //判断是否路径存在cookie
        if(this.$route.query.openid){ 
            this.setCookie(wapCookie, this.$route.query.openid, 2)  
        }else if(this.getCookie(wapCookie) != '' && this.getCookie(wapCookie) != 'undefined'){
            //判断cookie是否存在openid
            console.log("存在openid");
        }else{
            //授权
            location.href = 'http://sanly.mynatapp.cc/weharvest/wechat/authorize' +'?resultUrl='+ encodeURIComponent(window.document.location.href)
        }
        // 获取请求
        const cookieValue = this.getCookie(wapCookie)
        const  params = {openid : cookieValue, url: window.location.href.split('#')[0] }
        Api.wechat.authorize(params).then(this.jssdk)
    },
    methods : {
        setCookie (name, value, expiredays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            document.cookie = name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
        },
        getCookie(name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)")
            if (arr = document.cookie.match(reg)){
                return arr[2]
            }else{
                return ''
            }
        },
        deleteCookie (name) {
            var exp = new Date()
            exp.setTime(exp.getTime() - 1)
            var cval = this.getCookie(name)
            if (cval != null)
            document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()
        },
        jssdk(res){
            if(res.data.code ==0){
                //ticket:sM4AOVdWfPE4DxkXGEs8VOOqLwfNQzLL_yYdfcBFYrMvAGTpZMtHi9bpB5tpsdPDGmgp9QnABNEEJjnrClzoiQ
                const  jssdkValue = res.data.data
                alert(location.href.split('#')[0]);
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: jssdkValue.appId, // 必填，公众号的唯一标识
                    timestamp: jssdkValue.timestamp, // 必填，生成签名的时间戳
                    nonceStr:  jssdkValue.nonceStr, // 必填，生成签名的随机串
                    signature: jssdkValue.signature,// 必填，签名
                    jsApiList: [
                        'checkJsApi','chooseImage',
                        'startRecord','stopRecord',
                        'playVoice','onVoiceRecordEnd',
                        'pauseVoice','stopVoice',
                        'onVoicePlayEnd','uploadVoice',
                        'downloadVoice'
                        ] // 必填，需要使用的JS接口列表
                })
                // 成功调用
                wx.ready(function(){
                    console.log('ready')
                    //录音计时,小于指定秒数(minTime = 10)则设置用户未录音  
                    var startTime , endTime , minTime = 2;  
                    //保存录音id
                    var  localId
                    /*************开始录音  **************/
                    $('.start_btn').on('touchstart',function(e){  
                        //阻止默认行为
                        e.preventDefault();  
                        //改变样式
                        $('.start_btn').css("background","#FF0000"); 
                        // var $this = $(this); 
                        // $this.addClass('start_btn_in'); 
                        startTime = new Date().getTime();          
                        //开始录音  
                        wx.startRecord();  
                    }); 

                    /************* 停止录音 **************/
                    $('.start_btn').on('touchend', function(){ 
                        //改变样式
                        $('.start_btn').css("background","#2aab0c"); 
                        // var $this = $(this);  
                        // $this.removeClass('start_btn_in');  
                        //停止录音接口  
                        wx.stopRecord({  
                            success: function (res) {  
                                endTime = new Date().getTime();  
                                alert((endTime - startTime) / 1000);  
                                if((endTime - startTime) / 1000 < minTime){  
                                    return  alert('录音少于' + minTime +  '秒，录音失败，请重新录音');  
                                } 
                                localId = res.localId;  
                            }  
                        });  
                    });

                    /************* 播放语音 **************/
                    $('.play_btn').on('click',function(){  
                        if(!localId){  
                            alert('您还未录音，请录音后再点击播放');  
                            return;  
                        }  
                        // 播放语音接口 
                        wx.playVoice({  
                            //需要播放的音频的本地ID，由 stopRecord 或 onVoiceRecordEnd 接口获得  
                            localId: localId  
                        });  
                    })  

                    /************* 上传录音 **************/
                    $('.send_btn').on('click',function(){
                        //调用微信的上传录音接口把本地录音先上传到微信的服务器
                        //不过，微信只保留3天，而我们需要长期保存，我们需要把资源从微信服务器下载到自己的服务器
                        if(!localId){  
                            alert('您还未录音，请录音后再点击上传');  
                            return;  
                        }  
                        wx.uploadVoice({
                            localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success: function (res) {
                                //把录音在微信服务器上的id（res.serverId）发送到自己的服务器供下载。
                                const data  = {serverId : res.serverId,userId: "99999"}
                                Api.wechat.uploadRecord(data).then(res =>{
                                   if(res.data.code == 0){
                                       alert("上传成功")
                                   }else{
                                       alert("上传失败")
                                   }

                                })
                            }
                        });
                    })

                })   
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.video{
    position: absolute;
    bottom: 10px;
     height: 150px;
     width: 100%;
     background-color: blue;
     z-index:99;
     div{
        height: 50px;
        /** 垂直居中 */
        display:flex;
        -webkit-align-items:center;
        align-items:center;
        -webkit-justify-content:center;
        justify-content:center;
        background: #2aab0c;
        border:1px solid blue;
        button{
            width: 100%;
            color: black;
            BACKGROUND-COLOR: transparent;
        }
    }     
}
.start_btn_in,.stop_btn_in{ 
     background: red;
     z-index: 2;
}  
</style>